import React from "react";
import { Search, Swiper, Image, Grid } from "react-vant";
import axios from "axios";
import './App.css'
class App extends React.Component {
  state = {
    banners: [],
    menus: [],
    customMenus: [],
    list: [],
  };
  getBanners = async () => {
    const resp = await axios.get("/api/banners");
    this.setState({
      banners: resp.data.data,
    });
  };
  getMenus = async () => {
    const resp = await axios.get("/api/menus");
    // 数据转换
    const data = [...resp.data.data];
    const result = [];
    
    while (data.length > 0) {
      const arr = data.splice(0, 2);
      result.push(arr);
    }

    // [{}]  => [ [{}, {}], [{}, {}] ]
 
    this.setState({
      menus: resp.data.data,
      customMenus: result,
    });
  };
  render() {
    const { banners, menus, customMenus } = this.state;
    return (
      <div>
        {/* 搜索 */}
        <Search background="#f00" placeholder="请输入搜索内容"></Search>
        {/* 轮播 */}
        <Swiper>
          {banners.map((v) => {
            return (
              <Swiper.Item key={v.id}>
                <Image src={v.image}></Image>
              </Swiper.Item>
            );
          })}
        </Swiper>
        {/* 导航 */}
        <Grid columnNum={5}>
          {menus.slice(0, 10).map((v) => {
            return (
              <Grid.Item
                key={v.id}
                icon={<Image src={v.image}></Image>}
                text={v.title}
              ></Grid.Item>
            );
          })}
        </Grid>
        {/* 自己实现 */}
        <div className="menus">
          {customMenus.map((v, i) => {
            return (
              <div className="menu-item" key={i}>
                {v.map((item) => {
                  return (
                    <dl key={item.id}>
                      <dt>
                        <img src={item.image} alt="" />
                      </dt>
                      <dd>
                        <h4>{item.title}</h4>
                      </dd>
                    </dl>
                  );
                })}
              </div>
            );
          })}
        </div>
      </div>
    );
  }
  componentDidMount() {
    this.getBanners();
    this.getMenus();
  }
}

export default App;
